package com.learn.concurrent.itcast.thread.lock;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 从运行结果可以看出，两个线程的读操作是同时执行的，整个过程大概耗时100ms。
 * 通过两次实验的对比，我们可以看出来，ReetrantReadWriteLock的效率明显高于Synchronized关键字。
 */
public class ReadAndWriteLockTest2 {

    final static ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();

    public static void get(Thread thread){
        readWriteLock.readLock().lock();
        System.out.println("start time:"+System.currentTimeMillis());
        for (int i = 0; i < 6; i++) {
            try {
                Thread.sleep(200);
                System.out.println(thread.getName()+"正在进行读操作");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(thread.getName()+"读操作完毕");
        System.out.println("end time"+System.currentTimeMillis());
        readWriteLock.readLock().unlock();

    }

    public static void main(String[] args) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                get(Thread.currentThread());
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                get(Thread.currentThread());
            }
        }).start();
    }
}
